<template>
  <div>
    <SearchForm @search="getTableData" @reset="resetSearch">
      <el-col :span="8" :xs="24" v-if="$permiss[1651]">
        <el-form-item :label="$t('所属租户')">
          <el-select style="width: 100%" v-model="page.adminUserId" clearable>
            <el-option v-for="item in tenantList" :key="item.adminUserId"
                       :label="item.adminName"
                       :value="item.adminUserId"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('标题')">
          <el-input v-model="page.title"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('状态')">
          <el-select style="width: 100%" v-model="page.status" clearable>
            <el-option :label="$t('启用')" :value="1"></el-option>
            <el-option :label="$t('禁用')" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('创建人')">
          <el-select style="width: 100%" v-model="page.creationName" clearable>
            <el-option v-for="item in optionsList" :key="item" :value="item" :label="item"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-form-item :label="$t('日期')">
          <el-date-picker
              v-model="page.timeValue"
              style="width: 100%"
              value-format="yyyy-MM-dd"
              unlink-panels
              type="daterange"
              range-separator="~"
              :start-placeholder="$t('开始时间')"
              :end-placeholder="$t('结束时间')">
          </el-date-picker>
        </el-form-item>
      </el-col>
    </SearchForm>
    <el-card shadow="never" style="margin-top: 10px">
      <div style="margin-bottom: 10px;text-align: right">
        <el-button type="primary" @click="addLabel" v-show="$permiss[1650]">{{ $t('新增') }}</el-button>
      </div>
      <Table :tableData="tableData" :tableColumn="tableColumn" :page="page"
             :loading="loading"
             @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange">
        <template slot="labelListStr" slot-scope="{row}">
          <el-tag v-for="item in formatLabel(row.labelListStr)" :disable-transitions="true" style="margin: 0 5px 5px 0 "
                  :key="item">{{
              item
            }}
          </el-tag>
        </template>
        <template slot="rate" slot-scope="{row}">
          <div v-if="row.rate" :style="{color:row.rateType === 1 ? '#e71212' : '#50e81a' }">
            <i :class="row.rateType === 1 ? 'el-icon-top' : 'el-icon-bottom' "
            /> {{ row.rate }}%
          </div>
        </template>
        <template slot="rateAmount" slot-scope="{row}">
          <div v-if="row.rateAmount" :style="{color:row.rateType === 1 ? '#e71212' : '#50e81a' }">
            <i :class="row.rateType === 1 ? 'el-icon-top' : 'el-icon-bottom' "/>
            {{ row.rateAmount }}
          </div>
        </template>
        <template slot="status" slot-scope="{row}">
          <el-switch :value="row.status === 1" :disabled="!$permiss[1649]" @change="changeStatus(row)"></el-switch>
        </template>
        <template slot="handle" slot-scope="{row}">
          <el-button type="text" v-show="$permiss[1649]" @click="editForm(row)">{{ $t('编辑') }}</el-button>
        </template>
      </Table>
    </el-card>
    <Dialog :visible.sync="visible.isShow" :title="visible.title" width="50%" @close="clearForm"
            @cancel="visible.isShow = false"
            @confirm="confirm">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item :label="$t('标题')" :rules="[
            {required: true,message: $t('不能为空')}
        ]" prop="title">
          <el-input v-model="form.title"  :disabled="visible.type === 'edit'" />
        </el-form-item>
        <el-form-item :label="$t('安装类型')" prop="installType">
          <el-radio-group v-model="form.installType" :disabled="visible.type === 'edit'" >
            <el-radio :label="10">{{ $t('不选择') }}</el-radio>
            <el-radio :label="1">{{ $t('自然量') }}</el-radio>
            <el-radio :label="2">{{ $t('投放量') }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('客户类型')" prop="userType">
          <el-checkbox-group v-model="form.userType" :disabled="visible.type === 'edit'">
            <el-checkbox :label="3">{{ $t('白名单') }}</el-checkbox>
            <el-checkbox :label="4">{{ $t('注册未申请') }}</el-checkbox>
            <el-checkbox :label="5">{{ $t('共享用户') }}</el-checkbox>
            <el-checkbox :label="6">{{ $t('转换用户') }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item :label="$t('初始可借金额')" prop="amount" :rules="[
            {required: true,message: $t('不能为空')}
        ]" label-width="120px">
          <el-input v-model="form.amount" style="width:200px" oninput="value = value.replace(/[^\d.]/g, '')"/>
          <el-alert
              style="margin-top:10px"
              :title="$t('该用户标签组合注册后,初始可借金额在原基础上提升')"
              type="info"
              show-icon
              :closable="false"
          >
          </el-alert>
        </el-form-item>
        <el-form-item :label="$t('初始服务费')" prop="rate" label-width="100px" :rules="[
            {required: true,validator: validatorFeeAmount
           }
        ]">
          <el-radio-group v-model="form.rateType">
            <el-radio :label="1">{{ $t('上调') }}</el-radio>
            <el-radio :label="2">{{ $t('下降') }}</el-radio>
          </el-radio-group>
          <div>
            <el-input style="width:180px;margin-left: 10px" placeholder="服务费利率" v-model="form.rate"
                      oninput="value = value.replace(/[^\d]/g, '')">
              <template slot="append">%</template>
            </el-input>
            <el-input style="width:180px;margin-left: 10px" placeholder="服务费金额" v-model="form.rateAmount"
                      oninput="value = value.replace(/[^\d]/g, '')">
            </el-input>
          </div>
          <el-alert
              style="margin-top:10px"
              title="服务费按金额和利率各配置一个，实际按客户所选择的借款金额，所配置的服务费方式进行"
              type="info"
              show-icon
              :closable="false"
          />
        </el-form-item>
        <el-form-item :label="$t('状态')" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">{{ $t('启用') }}</el-radio>
            <el-radio :label="0">{{ $t('禁用') }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('备注')" prop="remark">
          <el-input type="textarea" :rows="4" v-model="form.remark"/>
        </el-form-item>
      </el-form>
    </Dialog>
  </div>
</template>

<script>
import {fetchLabelComposeList, selectLabelCreationName, updateLabelCompose, addLabelCompose} from '@/api/product'
import {selectTenant} from '@/api/system'
import {dateFormatSection} from '@/utils/tools'

export default {
  name: "userLabelCompose",
  data() {
    return {
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      tableColumn: [
        {label: this.$t('标题'), prop: 'title'},
        {label: this.$t('标签组合'), prop: 'labelListStr', slot: 'labelListStr'},
        {label: this.$t('初始可借金额提升'), prop: 'amount', minWidth: 150},
        {label: this.$t('初始服务费金额'), prop: 'rateAmount', slot: 'rateAmount', minWidth: 150},
        {label: this.$t('初始服务费利率'), prop: 'rate', slot: 'rate', minWidth: 150},
        {label: this.$t('状态'), prop: 'status', slot: 'status'},
        {label: this.$t('备注'), prop: 'remark', minWidth: 150},
        {label: this.$t('创建时间'), prop: 'creationTime', minWidth: 150},
        {label: this.$t('创建人'), prop: 'creationName'},
        {label: this.$t('操作'), slot: 'handle', minWidth: 100, fixed: 'right'},
      ],
      tableData: [],
      tenantList: [],
      optionsList: [],
      loading: false,
      visible: {
        isShow: false,
        title: '',
        type: 'add',
      },
      form: {
        title: null,
        installType: 10,
        status: 1,
        rateAmount: null,
        rate: null,
        userType: [],
        rateType: 1,
      },
    }
  },
  mounted() {
    selectTenant().then(res => {
      this.tenantList = res.data
    })
    selectLabelCreationName().then(res => {
      this.optionsList = res.data
    })
    this.getTableData()
  },
  methods: {
    async getTableData() {
      const [startTime, endTime] = dateFormatSection(this.page.timeValue)
      const params = {
        ...this.page,
        startTime, endTime
      }
      delete params.timeValue
      this.loading = true
      const res = await fetchLabelComposeList(params)
      if (res.code === 1) {
        const {list, total} = res.data
        this.tableData = list
        this.page.total = total
        this.loading = false
      } else {
        this.loading = false
      }
    },
    addLabel() {
      this.visible = {
        isShow: true,
        title: this.$t('新增用户标签组合'),
        type: 'add'
      }
    },
    clearForm() {
      this.$refs.form.resetFields()
      // this.form = {
      //   title: null,
      //   installType: 1,
      //   status: 1,
      //   userType: [],
      //   rateType: 1,
      //   rateAmount: null,
      //   rate: null,
      // }
    },
    confirm() {
      this.$refs.form.validate(async v => {
        if (v) {
          const {title, status, remark, amount, userType, id, installType, rate, rateType, rateAmount} = this.form
          const params = {
            title, status, remark, amount, id,
            rate, rateType, rateAmount,
            labelList: [installType, ...userType].filter(item => item !== 10).join('&'),
          }
          const isAdd = this.visible.type === 'add'
          const res = isAdd ? await addLabelCompose(params) : await updateLabelCompose(params)
          if (res.code === 1) {
            this.getTableData()
            this.visible.isShow = false
            this.$message.success(isAdd ? this.$t('新增成功') : this.$t('编辑成功'))
          }
        }
      })
    },

    validatorFeeAmount(rules, value, callBack) {
      const {rate, rateAmount} = this.form
      if (!rate || !rateAmount) {
        return callBack(new Error('请填写利率和金额'))
      }
      return callBack()
    },
    editForm(row) {
      this.visible = {
        isShow: true,
        title: this.$t('编辑用户标签组合'),
        type: 'edit'
      }
      const {id, title, status, remark, amount, labelList, rateType, rate, rateAmount} = row
      const ininstallType = labelList.split('&').find(item => {
        return item === "1" || item === "2"
      })
      const userType = labelList.split('&').filter(item => {
        return item !== "1" && item !== "2"
      }).map(item => parseInt(item))
      this.form = {
        id, title, status, remark, amount, rateType, rate, rateAmount,
        installType: parseInt(ininstallType || 10),
        userType: userType
      }
    },
    resetSearch() {
      this.page = {
        pageNum: 1,
        pageSize: 10,
        total: 0
      }
      this.getTableData()
    },
    async changeStatus({status, id}) {
      const res = await updateLabelCompose({
        status: status === 1 ? 0 : 1,
        id
      })
      if (res.code === 1) {
        this.getTableData()
        this.$message.success(this.$t('操作成功'))
      }
    },
    formatLabel(value) {
      const tagsValue = value.split('&')
      return tagsValue
    },
    handleSizeChange(value) {
      this.page.pageSize = value
      this.getTableData()
    },
    handleCurrentChange(value) {
      this.page.pageNum = value
      this.getTableData()
    }
  }
}
</script>

<style scoped>

</style>
